package edu.kit.aifb.evtcrawl.pachube;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.HeaderIterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.codehaus.jackson.map.ObjectMapper;

import edu.kit.aifb.evtcrawl.pachube.structure.PachubeDatastream;
import edu.kit.aifb.evtcrawl.pachube.structure.PachubeFeed;

public class PachubeHandler {

	private String apikey;
	private DefaultHttpClient httpclient;
	private ObjectMapper mapper;

	public PachubeHandler(String apikey) {
		this.apikey = apikey;
		httpclient = new DefaultHttpClient();
		mapper = new ObjectMapper();
	}
	
	/**
	 * 
	 * @param feedId Id of the feed that the datastream is part of
	 * @param streamId Id (as String) of the datastream to retrieve the current item from
	 * @return An object of PachubeDataItem with the appropriate fields set or <b>null</b> if an error occured.
	 */
	public PachubeFeed getFeed(String feedId) {
		PachubeFeed result = null;
		try {
			URIBuilder builder = new URIBuilder();
			builder.setScheme("http")
					.setHost("api.cosm.com")
					.setPath("/v2/feeds/" + feedId);
			URI uri = builder.build();

			HttpGet httpget = new HttpGet(uri);
			httpget.addHeader("X-ApiKey", apikey);
			//httpget.addHeader("Accept", "application/xml");
			httpget.addHeader("Accept", "application/json");
			//printHeader(httpget);
			
			HttpResponse response = httpclient.execute(httpget);
			//printHeader(response);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				//InputStream instream = entity.getContent();
				String responseString = EntityUtils.toString(entity);
				//System.out.println("* ENTITY: " + responseString);
				if (response.getStatusLine().getStatusCode() == 200){
					result = mapper.readValue(responseString, PachubeFeed.class);
					//System.out.println(result);
				}
			}
		} catch (URISyntaxException e) {
			e.printStackTrace();
			return null;
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return result;
	}
	
	
	public PachubeDatastream getData(String feedId, String streamId) {
		int fId = Integer.parseInt(feedId);
		return getData(fId, streamId);
	}
	
	
	/**
	 * 
	 * @param feedId Id of the feed that the datastream is part of
	 * @param streamId Id (as String) of the datastream to retrieve the current item from
	 * @return An object of PachubeDataItem with the appropriate fields set or <b>null</b> if an error occured.
	 */
	public PachubeDatastream getData(int feedId, String streamId) {
		PachubeDatastream result = null;
		try {
			URIBuilder builder = new URIBuilder();
			builder.setScheme("http")
					.setHost("api.cosm.com")
					.setPath("/v2/feeds/" + feedId + "/datastreams/" + streamId);
			URI uri = builder.build();

			HttpGet httpget = new HttpGet(uri);
			httpget.addHeader("X-ApiKey", apikey);
			//httpget.addHeader("Accept", "application/xml");
			httpget.addHeader("Accept", "application/json");
			//printHeader(httpget);
			
			HttpResponse response = httpclient.execute(httpget);
			//printHeader(response);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				//InputStream instream = entity.getContent();
				String responseString = EntityUtils.toString(entity);
				//System.out.println("* ENTITY: " + responseString);
				if (response.getStatusLine().getStatusCode() == 200){
					result = mapper.readValue(responseString, PachubeDatastream.class);
				}
			}
		} catch (URISyntaxException e) {
			e.printStackTrace();
			return null;
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return result;
	}

	public static void printHeader(HttpGet get) {
		System.out.println("******Get Header:*********");
		System.out.println("* " + get.getRequestLine());
		System.out.println("* ------------------------");
		HeaderIterator it = get.headerIterator();
		while (it.hasNext()) {
			System.out.println("* " + it.next());
		}
		System.out.println("**************************");
	}

	public static void printHeader(HttpResponse resp) {
		System.out.println("******Response Header*****");
		System.out.println("* " + resp.getStatusLine());
		System.out.println("* ------------------------");
		HeaderIterator it = resp.headerIterator();
		while (it.hasNext()) {
			System.out.println("* " + it.next());
		}
		System.out.println("**************************");
	}
}
